import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'dva';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import {
  Divider,
  Button,
  Tooltip,
  message,
  Popconfirm,
  Badge,
  Spin,
  Modal,
  Input,
  Form,
  Select,
} from 'antd';
import {
  deviceMaster,
  deviceAdd,
  deviceUpdate,
  deviceDelete,
  deviceOnlineState,
  deviceRefreshConn,
  apiPushSingle,
} from '@/services/otherServices';
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  FileSearchOutlined,
  WifiOutlined,
  LoadingOutlined,
  SendOutlined,
} from '@ant-design/icons';
import Search from './Search';
import { history } from 'umi';
import Detail from './Detail';
import OnlineState from './OnlineState';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import {
  btnPermission,
  diffSubmitData,
  formatDate,
  mergeLoading,
} from '@/utils/utils';

const stateMap: any = {
  '8': '离线',
  '192': '在线',
};
let detailForm: any = null;

const List = (props: any) => {
  const { btnPermissionLoading } = props;
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);
  const [size, setSize]: any = useState('large');
  const [searchValue, setSearchValue] = useState({});
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize]: any = useState(10);
  const [dataSource, setDataSource] = useState([]);

  const [editId, setEditId] = useState(undefined);
  const [editItem, setEditItem] = useState(undefined);

  /*
   * 离在线记录
   * */
  const [onLineVisible, setOnLineVisible] = useState(false);
  const [onlineData, setOnlineData]: any = useState([]);
  const [onlineCurrent, setOnlineCurrent] = useState(1);
  const [onlineTotal, setOnlineTotal] = useState(1);
  const [deviceNo, setDeviceNo]: any = useState(undefined);
  const [noId, setNoId]: any = useState(undefined);

  /*
   * 消息推送
   * */
  const [pushVisible, setPushVisible] = useState(false);
  const [pushNo, setPushNo] = useState('');

  /*
   * 列表请求
   * */
  const { loading: pageLoading, run: getPage } = useRequest(deviceMaster, {
    manual: true,
    onSuccess: (res, params) => {
      setDataSource(res.data);
      setTotal(res.total);
    },
  });

  /*
   * 新建请求
   * */
  const { loading: addLoading, run: add } = useRequest(deviceAdd, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('添加设备成功');
      setVisible(false);
      getPageData();
    },
  });

  const { loading: pushLoading, run: push } = useRequest(apiPushSingle, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.destroy();
      message.success('推送成功');
      setPushVisible(false);
    },
  });
  /*
   * 编辑请求
   * */
  const { loading: updateLoading, run: update } = useRequest(deviceUpdate, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('更新设备成功');
      setVisible(false);
      getPageData();
    },
  });

  /*
   * 删除请求
   * */
  const { loading: delLoading, run: del } = useRequest(deviceDelete, {
    manual: true,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('删除设备成功');
      if (total % 10 === 1) {
        setCurrent(current - 1);
      } else {
        getPageData();
      }
    },
  });

  /*
   * 设备状态列表请求
   * */
  const { loading: onlineStateLoading, run: onlineState } = useRequest(
    deviceOnlineState,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        setOnlineData(res.data);
        setOnlineCurrent(res.pageNo);
        setOnlineTotal(res.total);
      },
    },
  );

  /*
   * 设备探测
   * */
  const { run: runRefreshConn, fetches: refreshConnLoading } = useRequest(
    deviceRefreshConn,
    {
      manual: true,
      throttleInterval: 500,
      loadingDelay: 200,
      fetchKey: deviceNo => deviceNo,
      onSuccess: (res, params) => {
        // 在线状态
        message.success(res.message);
      },
    },
  );

  const getOnlineStateData = (deviceNo: string) => {
    setDeviceNo(deviceNo);
    onlineState({
      deviceNo: deviceNo,
      pageNo: onlineCurrent,
      pageSize: 10,
    });
  };

  const getPageData = () => {
    getPage({
      pageNo: current,
      pageSize: pageSize,
      ...searchValue,
    });
  };

  useUpdateEffect(() => {
    getPageData();
  }, [current, pageSize, searchValue]);

  useUpdateEffect(() => {
    getOnlineStateData(deviceNo);
  }, [onlineCurrent]);

  useEffect(() => {
    getPageData();
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '编号',
      dataIndex: 'a',
      render: (text, record, index) => (
        <span>{(current - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: '公司名',
      dataIndex: 'company',
    },
    {
      title: '设备编号',
      dataIndex: 'deviceNo',
    },
    {
      title: '产线名',
      dataIndex: 'productLine',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'quality',
      render: text => (
        <Badge
          status={text !== 8 ? 'success' : 'error'}
          text={stateMap[text + '']}
        />
      ),
    },
    {
      title: '固件版本',
      dataIndex: 'firmwareVersion',
    },
    {
      title: 'WIFI状态',
      dataIndex: 'wifiStatus',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      render: text => <span>{formatDate(text)}</span>,
    },
  ];
  if (
    btnPermission(history.location.pathname, [
      'btn_dev_edit',
      'btn_dev_del',
      'btn_dev_online',
      'btn_dev_detect',
    ])
  ) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      render: (_, record) => (
        <>
          {btnPermission(history.location.pathname, 'btn_dev_edit') && (
            <span>
              <a
                onClick={() => {
                  detailForm.setFieldsValue({
                    ...record,
                  });
                  setVisible(true);
                  setEditId(record.id);
                  setEditItem(record);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="编辑">
                  <FormOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_dev_del') && (
            <span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除？"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(record.id);
                }}
              >
                <a>
                  <Tooltip mouseEnterDelay={0.5} title="删除">
                    <DeleteOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_dev_online') && (
            <span>
              <Divider type="vertical" />
              <a
                onClick={() => {
                  getOnlineStateData(record.deviceNo);
                  setOnLineVisible(true);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="离在线详情">
                  <FileSearchOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_dev_detect') && (
            <span>
              <a
                onClick={() => {
                  runRefreshConn(record.deviceNo);
                }}
              >
                <Divider type="vertical" />
                <Tooltip mouseEnterDelay={0.5} title="探测">
                  {refreshConnLoading[record.deviceNo]?.loading ? (
                    <LoadingOutlined style={{ fontSize: 18 }} />
                  ) : (
                    <WifiOutlined style={{ fontSize: 18 }} />
                  )}
                </Tooltip>
              </a>
            </span>
          )}
          {/*{btnPermission(history.location.pathname, 'btn_dev_detect') && (*/}
          {/*  <span>*/}
          {/*    <a*/}
          {/*      onClick={() => {*/}
          {/*        setPushNo(record.deviceNo);*/}
          {/*        setPushVisible(true);*/}
          {/*      }}*/}
          {/*    >*/}
          {/*      <Divider type="vertical" />*/}
          {/*      <Tooltip mouseEnterDelay={0.5} title="推送">*/}
          {/*        <SendOutlined style={{ fontSize: 18 }} />*/}
          {/*      </Tooltip>*/}
          {/*    </a>*/}
          {/*  </span>*/}
          {/*)}*/}
        </>
      ),
    });
  }

  const pushModal = () => {
    const [form] = Form.useForm();
    return (
      <Modal
        title="消息推送"
        visible={pushVisible}
        onCancel={() => setPushVisible(false)}
        afterClose={() => {
          setPushNo('');
          form.resetFields();
        }}
        onOk={() => {
          if (
            form.getFieldValue('msg') === '' ||
            form.getFieldValue('msg') === undefined
          ) {
            message.destroy();
            message.error('请输入推送内容');
            return;
          }
          push({
            deviceNo: pushNo,
            msg: form.getFieldValue('msg'),
          });
        }}
        okButtonProps={{ loading: pushLoading }}
      >
        <Form
          hideRequiredMark
          style={{ marginTop: 8 }}
          form={form}
          name="basic"
        >
          <Form.Item name={'msg'}>
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  return (
    <div className={'spin-bg-white'}>
      {pushModal()}
      <Spin tip={'权限获取中,请稍等...'} spinning={btnPermissionLoading}>
        <Detail
          afterClose={() => {
            setEditId(undefined);
            setEditItem(undefined);

            detailForm.resetFields();
          }}
          visible={visible}
          onCancel={() => setVisible(false)}
          getForm={(from: any) => (detailForm = from)}
          loading={mergeLoading(addLoading, updateLoading)}
          editId={editId}
          onOk={async () => {
            await detailForm.validateFields();
            if (editId) {
              const data = diffSubmitData(
                editItem,
                detailForm.getFieldsValue(),
              );
              update({
                id: editId,
                ...data,
              });
            } else {
              add(detailForm.getFieldsValue());
            }
          }}
        />
        <OnlineState
          loading={onlineStateLoading}
          current={onlineCurrent}
          pageChange={(current: number) => {
            setOnlineCurrent(current);
          }}
          afterClose={() => {
            setOnlineData([]);
            setOnlineCurrent(1);
            setOnlineTotal(1);
            setDeviceNo(undefined);
          }}
          total={onlineTotal}
          onlineData={onlineData}
          visible={onLineVisible}
          onCancel={() => setOnLineVisible(false)}
        />
        <ProTable<any>
          loading={pageLoading}
          dataSource={dataSource}
          actionRef={actionRef}
          tableAlertRender={false}
          search={false}
          scroll={{ x: 'max-content' }}
          options={{
            fullScreen: false,
            density: true,
            reload: false,
            setting: true,
          }}
          rowKey="id"
          size={size}
          onSizeChange={(s: any) => {
            setSize(s);
          }}
          headerTitle={
            <Search
              loading={pageLoading}
              noId={noId}
              callbackValue={(value: any) => {
                setCurrent(1);
                setSearchValue(value);
              }}
            />
          }
          toolBarRender={(action, { selectedRows }) => [
            btnPermission(history.location.pathname, 'btn_dev_add') && (
              <Button
                onClick={() => setVisible(true)}
                icon={<PlusOutlined />}
                type="primary"
              >
                新建
              </Button>
            ),
          ]}
          pagination={{
            pageSize: pageSize,
            total: total,
            current: current,
            onChange: (page, pageSize) => {
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {
              setCurrent(current);
              setPageSize(size);
            },
          }}
          columns={columns}
          rowSelection={{
            type: 'radio',
            onChange: (selectedRowKeys, selectedRows: any) => {
              setNoId(selectedRows[0] && selectedRows[0].deviceNo);
            },
          }}
        />
      </Spin>
    </div>
  );
};
export default connect(({ globalModel }: any) => ({
  btnPermissionLoading: globalModel.btnPermissionLoading,
}))(List);
